<template>
  <!-- 员工 -->
  <div class="dashboard-container">
    <div class="app-container">
      <!-- title -->
      <Page-Tools show-before>
        <template v-slot:before>
          <span> {{ `一共条${page.total}数据` }} </span>
        </template>
        <template v-slot:after>
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportDate">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </Page-Tools>
      <!-- title -->
      <!-- 表格 -->
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" sortable="" type="index" width="100" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <!-- <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatterhireType"/> -->
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatterhireType">
            <template v-slot="{row}">
              {{ row.formOfEmployment|hireType }}
            </template>
          </el-table-column>
          <el-table-column label="头像">
            <template slot-scope="{row}">
              <img
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto?row.staffPhoto:require('@/assets/common/bigUserHeader.png')"
                alt=""
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <!-- <el-table-column label="入职时间" sortable="" prop="timeOfEntry" /> -->
          <el-table-column label="入职时间" sortable="" align="center">
            <!-- 作用域插槽 -->
            <template v-slot="{ row }">{{ row.timeOfEntry | formatDate }}</template>
          </el-table-column>
          <!-- <el-table-column label="账户状态" sortable="" prop="enableState" /> -->
          <el-table-column label="账户状态" align="center" sortable="" prop="enableState">
            <template v-slot="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 0" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 表格 -->
      <!-- 分页 -->
      <el-row
        type="flex"
        justify="center"
        align="middle"
        style="height: 60px"
      >
        <el-pagination
          layout="prev, pager, next"
          :current-page="page.page"
          :page-size="page.size"
          :total="page.total"
          @current-change="changepage"
        >
        </el-pagination>
      </el-row>
      <!-- 分页 -->
      <!-- 对话框 -->
      <!-- 新增对话框 -->
      <Add-Employee :show-dialog.sync="showDialog" />
      <!-- 二维码对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="showCodeDialog"
        width="50%"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas"></canvas>
        </el-row>

      </el-dialog>
      <!-- 角色分配对话框 -->
      <AssginRole ref="assginRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees.js'
import EmployeesEnum from '@/api/constant/employees.js'
import AddEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
import AssginRole from './components/assgin-role.vue'

export default {
  name: 'Employees',
  components: {
    AddEmployee, // 新增
    AssginRole// 角色
  },
  filters: {
    hireType(val) {
      const f = EmployeesEnum.hireType.find(t => t.id === val

      )
      return f ? f.value : '未知'
    }
  },
  props: {},
  data() {
    return {
      showDialog: false,
      list: [], // 员工数据
      page: {
        page: 1,
        size: 50,
        total: 0
      }, //
      loading: false, // 表格数据loading状态
      showCodeDialog: false, // 二维码弹框状态
      showRoleDialog: false, // 角色对话框状态
      userId: undefined// 当前点击用户的id
    }
  },
  created() {
    this.getEmployeeList()
  },
  mounted() {

  },

  methods: {
    // 获取员工数据
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      if (rows.length === 0 && this.page.page > 1) {
        this.page.page--
        this.getEmployeeList()
      }
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    // 下一页
    changepage(newPage) {
      // 修改数据
      this.page.page = newPage
      // 重新获取页面数据
      this.getEmployeeList()
    },
    // 聘请方式
    formatterhireType(row, column, cellValue, index) {
      const f = EmployeesEnum.hireType.find(t => t.id === cellValue
      )
      return f ? f.value : '未知'
    },
    // 删除员工信息
    delEmployee(id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        await delEmployee(id)
        this.$message.success('删除成功')
        this.getEmployeeList()// 重新获取数据
      }).catch(() => {

      })
    },
    // 修改新增员工对话框状态
    showdialogVisible() {
      this.dialogVisible = true
    },
    // 导出
    async exportDate() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
      // 得到值的对应英文值
      const value = Object.values(headers)
      const data = rows.map(item => {
        const a = value.map(keys => {
          // 转化时间格式
          if (keys === 'timeOfEntry' || keys === 'correctionTime') {
            return formatDate(item[keys])
          }
          // 转化聘用形式
          if (keys === 'formOfEmployment') {
            const f = EmployeesEnum.hireType.find(t => t.id === item[keys])
            return f ? f.value : '未知'
          }
          return item[keys]
        })
        return a
      })
      import('@/vendor/Export2Excel.js').then(excel => {
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: 'excel-list',
          autoWidth: false,
          bookType: 'xlsx',
          multiHeader: [['姓名', '主要信息', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2']
        })
      })
    },
    // 点击图片生成二维码
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 角色
    async editRole(id) {
      this.userId = id
      this.showRoleDialog = true
      await this.$refs.assginRole.getUserDetailById(id)
    }

  }
}
</script>

<style lang="scss" scoped>
</style>
